import React, { FC, useRef } from 'react'
import type { ActionType, ProColumns } from '@ant-design/pro-table'
import ProTable from '@ant-design/pro-table'
import { Popconfirm, Button, message } from 'antd'
import { EnvironmentDTO } from '@/model/efficient/EnvironmentDTO'
import { environmentPage, environmentRemove } from '@/api/efficient/environment'
import { ModelFormModeEnum } from '@/enums/ModelFormModeEnum'
import EnvironmentSetServerForm from './components/EnvironmentSetServerForm'
import EnvironmentForm from './components/EnvironmentForm'

import './index.scss'

const Environment: FC = () => {
  const actionRef = useRef<ActionType>()

  // 事件
  const environmentRemoveOnConfirm = async (record: EnvironmentDTO) => {
    await environmentRemove(record.id)
    message.success(`已删除 ${record.name}`)
    await actionRef.current.reload()
  }

  // 表格列
  const columns: ProColumns<EnvironmentDTO>[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'indexBorder',
      width: 48,
    },
    {
      title: 'code',
      dataIndex: 'code',
    },
    {
      title: '名称',
      dataIndex: 'name',
      ellipsis: true,
    },
    {
      title: '负责人',
      dataIndex: 'principal',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      copyable: true,
      ellipsis: true,
      search: false,
    },
    {
      title: '操作',
      valueType: 'option',
      render: (text, record) => [
        <EnvironmentSetServerForm environmentId={record.id} key={record.id} />,
        <EnvironmentForm
          mode={ModelFormModeEnum.update}
          row={record}
          actionRef={actionRef}
          key={record.id}
        />,
        <Popconfirm
          title="确认删除吗?"
          okText="是"
          cancelText="否"
          onConfirm={() => { environmentRemoveOnConfirm(record) }} // 点击确认的回调
          key={record.id}
        >
          <Button type="link">删除</Button>
        </Popconfirm>,
      ],
    },
  ]

  return (
    <div className="environment">
      <ProTable<EnvironmentDTO>
        columns={columns}
        actionRef={actionRef}
        request={async (params = {}) => {
          const data = await environmentPage(params)
          return {
            data: data.records,
            success: true,
            total: data.total,
          }
        }}
        columnsState={{
          persistenceKey: 'pro-table-environment',
          persistenceType: 'localStorage',
        }}
        rowKey="id"
        search={{
          labelWidth: 'auto',
        }}
        pagination={{
          pageSize: 10,
        }}
        dateFormatter="string"
        headerTitle="环境"
        toolBarRender={() => [
          <EnvironmentForm mode={ModelFormModeEnum.add} actionRef={actionRef} />,
        ]}
      />
    </div>
  )
}

export default Environment
